/***
 * Copyright (c) 2021-2031 murenchao
 * fig is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.software.fig.scriptutils

import java.io.Serializable
import java.util.ArrayList
import org.apache.commons.io.IOUtils
import org.jruby.Ruby
import org.jruby.javasupport.JavaEmbedUtils
import org.jruby.runtime.builtin.IRubyObject
import org.slf4j.LoggerFactory

class JRubyScript implements IFigScript, AutoCloseable {
	val static LOG = LoggerFactory.getLogger(JRubyScript)
	Ruby runtime
	IRubyObject rubyObject

	new(String path) {
		LOG.info(String.format("加载脚本:%s",path))
		var scriptInput = Thread.currentThread.contextClassLoader.getResourceAsStream(path)
		var loadPaths = new ArrayList<String>();
		loadPaths.add("/root/.jruby/lib/ruby/1.8");
		loadPaths.add("/root/.jruby/lib/ruby/site_ruby/1.8");
		runtime = JavaEmbedUtils.initialize(loadPaths);
		var evaler = JavaEmbedUtils.newRuntimeAdapter();
		rubyObject = evaler.eval(runtime, IOUtils.toString(scriptInput, "UTF-8"));
	}

	override <K, T extends Serializable> K invoke(String name, T value) {
		var result = JavaEmbedUtils.invokeMethod(runtime, rubyObject, name, newArrayList(value), Object);
		return result !== null ? result as K
	}

	override close() throws Exception {
	}

}
